//
//  HealthViewController.m
//  BigToBig
//
//  Created by admin on 16/4/29.
//  Copyright © 2016年 cn.cloudtp. All rights reserved.
//

#import "HealthViewController.h"
#import "PlayUserModel.h"
#import "PlayModel.h"
#import "HealthViewController.h"
#import "PlayMoveViewController.h"
static int p = 0;
static int offset = 0;
static int each = 2;


@interface HealthViewController()<UITableViewDataSource,UITableViewDelegate>

{
    
    UIView *lineView;

}
@property (nonatomic ,weak)UITableView *HealthTab;
@property (nonatomic ,strong)NSMutableArray *HealthArray;
@property (nonatomic ,strong)NSMutableArray *UserModelAray;
@property (nonatomic ,weak)UIImageView *imageView;


@end
@implementation HealthViewController
- (void)viewDidLoad {
    
    [super viewDidLoad];

    NSMutableArray *HealthArray = [NSMutableArray array];
    self.HealthArray = HealthArray;

    //设置系统自带的tableview不能滚动
//    self.tableView.scrollEnabled = NO;

    UITableView *HealthTab = [[UITableView alloc]initWithFrame:CGRectMake(0, 100, kScreenWidth, kScreenHeight - 149)];
    self.HealthTab = HealthTab;
    self.HealthTab.separatorStyle = UITableViewCellSeparatorStyleNone;
    HealthTab.delegate = self;
    HealthTab.dataSource = self;
    //    selfPlayTab.backgroundColor = [UIColor redColor];
    [self.view addSubview:HealthTab]; 
    self.HealthTab.showsVerticalScrollIndicator = NO;
    self.HealthTab.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loaddata1)];
    self.HealthTab.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    // 马上进入刷新状态
    [self.HealthTab.mj_header beginRefreshing];


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadData{
    
    [self.imageView removeFromSuperview];
    
    //    Reachability *reach = [Reachability reachabilityForInternetConnection];
    //    NetworkStatus status = [reach currentReachabilityStatus];
    //    if (status == NotReachable) {
    //
    //
    //        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
    //        HUD.labelText = @"请检查网络连接";
    //        HUD.mode = MBProgressHUDModeText;
    //        [HUD hide:YES afterDelay:1.0];
    //        [self.CarTab.mj_header endRefreshing];
    //
    //        UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    //        imageView.image = [UIImage imageNamed:@"not_data"];
    //        self.imageView = imageView;
    //        imageView.backgroundColor = [UIColor whiteColor];
    //        imageView.contentMode = UIViewContentModeCenter;
    //
    //        [self.CarTab addSubview:imageView];
    //
    //        return;
    //
    //    }
    offset = 0;
    [self.HealthArray removeAllObjects];
    
    NSLog(@"%ld",self.HealthArray.count);
    
    NSString *count = [NSString stringWithFormat:@"%d",p * 2];
    NSLog(@"%@",count);
    NSDictionary *params = @{@"category":@"25",@"offset":@"0",@"each":@"2",@"site_id":@"0"};
    [HttpTool postWithURL:@"http://61.135.176.43:6080/bigtobig/live/search?" params:params success:^(id json) {
        
        NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        NSMutableArray *userModelArray = [NSMutableArray array];
        self.UserModelAray = userModelArray;
        NSMutableArray *InternetArray = dict[@"live"];
        
        for (int i = 0; i < InternetArray.count; i++) {
            
            NSDictionary *dict = InternetArray[i];
            
            NSMutableDictionary *ObliveDict = dict[@"obj_live"];
            NSMutableDictionary *userDict = dict[@"user"];
            
            //字典转模型
            PlayModel *HealthMD = [PlayModel PlayModelWithDict:ObliveDict];
            
            PlayUserModel *HealthUserMD = [PlayUserModel PlayUserModelWithDict:userDict];
            
            [self.HealthArray addObject:HealthMD];
            
            [self.UserModelAray addObject:HealthUserMD];

            
        }
        if (self.HealthArray.count == 0) {
            
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
            imageView.image = [UIImage imageNamed:@"not_data"];
            self.imageView = imageView;
            imageView.backgroundColor = [UIColor whiteColor];
            
            imageView.contentMode = UIViewContentModeCenter;
            
            [self.HealthTab addSubview:imageView];
        }
        
        NSLog(@"%@",self.HealthArray);
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.HealthTab reloadData];
            
        });
        p++;
        //        [self.CarTab.mj_footer endRefreshing];
        [self.HealthTab.mj_header endRefreshing];
    } failure:^(NSError *error) {
        
        [self.HealthTab.mj_header endRefreshing];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.HealthTab reloadData];
            
            MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
            HUD.labelText = @"网络请求失败";
            HUD.mode = MBProgressHUDModeText;
            [HUD hide:YES afterDelay:1.0];
            
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
            imageView.image = [UIImage imageNamed:@"not_data"];
            self.imageView = imageView;
            imageView.contentMode = UIViewContentModeCenter;
            imageView.backgroundColor = [UIColor whiteColor];
            [self.HealthTab addSubview:imageView];
            
        });
        
    }];
    
    //    }
    
    
}
- (void)loaddata1{
    

    offset = offset + each;
    
    NSString *str = [NSString stringWithFormat:@"%d",offset];
    NSDictionary *params = @{@"category":@"25",@"offset":str,@"each":@"2",@"site_id":@"0"};
    
    [HttpTool postWithURL: @"http://61.135.176.43:6080/bigtobig/live/search?" params:params success:^(id json) {
        
        NSLog(@"%@",json);
        NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        NSMutableArray *JinRongArray = dict[@"live"];
        
        
        for (int i = 0; i < JinRongArray.count; i++) {
            
            
            NSDictionary *dict = JinRongArray[i];
            NSMutableDictionary *userDict = dict[@"user"];
            PlayUserModel *JinRongUserMD = [PlayUserModel PlayUserModelWithDict:userDict];
            
            NSMutableDictionary *ObliveDict = dict[@"obj_live"];
            PlayModel *JinRongMD = [PlayModel PlayModelWithDict:ObliveDict];
            
            //字典转模型
            [self.HealthArray addObject:JinRongMD];
            [self.UserModelAray addObject:JinRongUserMD];
            
            NSLog(@"%@",JinRongMD.category);
            NSLog(@"%@",JinRongUserMD.userid);
            
        }
        

        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.HealthTab reloadData];
            
        });
        
        p++;
        
        [self.HealthTab.mj_footer endRefreshing];
//        [self.HealthTab.mj_header endRefreshing];
        
    } failure:^(NSError *error) {
        
        NSLog(@"%@",error.userInfo);
        [self.HealthTab reloadData];

        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
        HUD.labelText = @"网络请求失败";
        HUD.mode = MBProgressHUDModeText;
        [HUD hide:YES afterDelay:1.0];
        
//        UIImageView *noDataImage = [[UIImageView alloc]initWithFrame:self.HealthTab.bounds];
//        noDataImage.backgroundColor = [UIColor whiteColor];
//        noDataImage.contentMode = UIViewContentModeCenter;
//        noDataImage.image = [UIImage imageNamed:@"not_data"];
//        [self.HealthTab addSubview:noDataImage];

        [self.HealthTab.mj_footer endRefreshing];
//        [self.HealthTab.mj_header endRefreshing];
    }];
    
}
- (NSString *)md5HexDigest:(NSString*)password
{
    
    const char *original_str = [password UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(original_str, strlen(original_str), result);
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
    {
        [hash appendFormat:@"%02X", result[i]];
    }
    NSString *mdfiveString = [hash lowercaseString];
    
    NSLog(@"Encryption Result = %@",mdfiveString);
    return mdfiveString;
}
#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    

    return self.HealthArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //为了防止cell重用设置唯一的cellID
    NSString *cellID = [NSString stringWithFormat:@"Cell%ld%ld",(long)[indexPath section],(long)[indexPath row]];
    
//    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    if (cell==nil) {
        
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];

    }
    

    if (self.HealthArray.count>0) {
        
        PlayModel *HealthMD = self.HealthArray[indexPath.row];
        PlayUserModel *HealthUserMD = self.UserModelAray[indexPath.row];

        //设置cell上的label
        UILabel *titleLb = [[UILabel alloc]initWithFrame:CGRectMake(75, 17.5f, 100, 20)];
        titleLb.font = [UIFont systemFontOfSize:12.0];
        //        titleLb.text = @"创业生态园";
        titleLb.text = HealthMD.theme;
       UILabel *VMRnumberLb = [[UILabel alloc]initWithFrame:CGRectMake(75, 37.5, 100, 20)];
        //    VMRnumberLb.text = Vm.conference_name;
        VMRnumberLb.text = @"路演项目";
        VMRnumberLb.font = [UIFont systemFontOfSize:12.0];

       UILabel *useCountLb = [[UILabel alloc]initWithFrame:CGRectMake(230, 15.0f, 100, 30)];
//        useCountLb.text = @"1.2万人次观看";
        useCountLb.font = [UIFont systemFontOfSize:12.0];
        
        NSDictionary *params = @{@"activityId":HealthMD.active_id};
        [HttpTool postWithURL:@"http://sdk2.karat.tv:8081/activity/onlineVeiwers?" params:params success:^(id json) {
            
            NSString *str = json[@"payload"];
            NSLog(@"%@",str);
            NSString *pepoleCountStr = [NSString stringWithFormat:@" %@人在线",str];
            useCountLb.text = pepoleCountStr;
            
        } failure:^(NSError *error) {
            
            
        }];

        //设置头像图片
       UIImageView *imageView =[[UIImageView alloc]init];
//        [imageView setImage:[UIImage imageNamed:@"tx"]];
        imageView.frame = CGRectMake(15.0f,7, 45, 45);
        imageView.layer.masksToBounds = YES;
        imageView.layer.cornerRadius = 27;
        
        NSString *uidStr = [NSString stringWithFormat:@"%@",HealthUserMD.userid];
        
        NSString *str1 = [self md5HexDigest:uidStr];
        
        NSString *b = [str1 substringWithRange:NSMakeRange(8,16)];
        NSString *str2 = @".png";
        NSString *imgName = [NSString stringWithFormat:@"%@%@",b,str2];
        NSLog(@"%@",imgName);
        NSString *HeadImageUrl = [NSString stringWithFormat:@"http://172.16.52.24:8030/data/HeadPortrait/%@",imgName];
        
        NSLog(@"%@",HeadImageUrl);
        
        //        NSLog(@"%@",JinRongMD.front_cover);
        
        UIImageView *imageView1 = [[UIImageView alloc]init];
        
        [imageView1 sd_setImageWithURL:[NSURL URLWithString:HeadImageUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            //设置头像图片
            if (error) {
                
                [imageView setImage:[UIImage imageNamed:@"tx"]];
                
                return ;
            }
            imageView.image = imageView1.image;
            
            
        }];
        
        
       UIButton *PlayBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 61, kScreenWidth, 180)];
        
        PlayBtn.tag = indexPath.row;

        NSString *str = [NSString stringWithFormat:@"http://61.135.176.43:6080/data/FrontCover/%@",HealthMD.front_cover];
        NSLog(@"%@",HealthMD.front_cover);
        NSLog(@"%@",str);
        
        UIImageView *imageView2 = [[UIImageView alloc]init];

        [imageView2 sd_setImageWithURL:[NSURL URLWithString:str] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            
            [PlayBtn setImage:imageView2.image forState:UIControlStateNormal];
            
        }];

        [PlayBtn addTarget:self action:@selector(playScreen:) forControlEvents:UIControlEventTouchUpInside];
        
        
        lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 60, kScreenWidth, 1)];
        lineView.backgroundColor = [UIColor grayColor];
        
       UIImageView *PlayView = [[UIImageView alloc]initWithFrame:CGRectMake((kScreenWidth - 59)/2 , (PlayBtn.height - 59)/2, 59, 59)];
        PlayView.image = [UIImage imageNamed:@"bf"];
        [PlayBtn addSubview:PlayView];
        
        [cell.contentView addSubview:PlayBtn];
        [cell.contentView addSubview:lineView];
        [cell.contentView addSubview:imageView];
        [cell.contentView addSubview:VMRnumberLb];
        [cell.contentView addSubview:titleLb];
        [cell.contentView addSubview:useCountLb];
    }
        
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    

    return 240;
}

- (void)playScreen:(UIButton *)btn{
    
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    if (status == NotReachable) {
        
        
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
        HUD.labelText = @"请检查网络连接";
        HUD.mode = MBProgressHUDModeText;
        [HUD hide:YES afterDelay:1.0];
        
        return;
        
    }
    PlayUserModel *healthUserMD = self.UserModelAray[btn.tag];
    PlayModel *healthModel = self.HealthArray[btn.tag];
    
    PlayMoveViewController *playMove = [[PlayMoveViewController alloc]init];
    NSString *playActive_id = [NSString stringWithFormat:@"%@",healthModel.active_id];
    playMove.playStr = playActive_id;
    ;
    
    NSLog(@"%@",playMove.playStr);
    
    
    
    playMove.userID = healthUserMD.userid;
    
    playMove.nameStr = healthUserMD.name;
    playMove.origentionScreen = healthModel.transform;

    [[(MainTabBarController *)KeyWindow.rootViewController selectedViewController]presentViewController:playMove animated:YES completion:nil];
    
    NSLog(@"播放视频");
    
    
}


@end
